package net.zkbc.helloworld.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import net.zkbc.helloworld.util.Urls;
import net.zkbc.helloworld.util.Views;
import net.zkbc.shared.service.LoginAttemptsService;
import net.zkbc.shiro.authc.IncorrectCaptchaException;

@Controller
public class HomeController {

	private static final Logger LOG = LoggerFactory.getLogger(HomeController.class);

	@Autowired
	private LoginAttemptsService loginAttemptsService;

	@RequestMapping(value = { "/", Urls.INDEX }, method = RequestMethod.GET)
	public String index() {
		return Views.INDEX;
	}

	@RequestMapping(value = Urls.LOGIN, method = RequestMethod.GET)
	public String loginForm() {
		return Views.LOGIN;
	}

	@RequestMapping(value = Urls.LOGIN, method = RequestMethod.POST)
	public String login(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String username, Exception e,
			RedirectAttributes redirectAttributes, HttpServletRequest request) {
		LOG.info("登录失败：username={}", username);

		if (e instanceof IncorrectCaptchaException) {
			redirectAttributes.addFlashAttribute("error", "验证码错误");
		} else {
			redirectAttributes.addFlashAttribute("error", "用户名或密码错误");
		}

		if (loginAttemptsService.loginCaptchaRequired(username)) {
			redirectAttributes.addFlashAttribute("loginCaptchaRequired", "required");
		}

		return "redirect:" + Urls.LOGIN;
	}

}
